﻿using System;
using System.Collections.Generic;
using System.Text;
using PreeRegisterModel;
using Newtonsoft.Json.Linq;
using System.Web;
using Newtonsoft.Json;
using System.Timers;
using System.Linq;

namespace PreeRegisterBLL
{
    /// <summary>
    /// 长治和平接口
    /// </summary>
    public class ChangZhiHePingBLL
    {
        #region 调用接口返回

        #region 预约挂号&支付
        /// <summary>
        /// 获取科室信息（获取所有科室）
        /// 请求URL：http://192.168.30.202:8044/WebInterface/GetOutpatientDepartments?parameters
        /// </summary>
        /// <returns></returns>
        public static JObject GetOutpatientDepartments()
        {
            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutpatientDepartments?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{");
            body.Append("{head:\"\",");
            body.Append("body:\"\"");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            obj_return = CommonBLL.HttpPost_CZHP(url);
            return obj_return;
        }

        /// <summary>
        /// 获取科室下的医生
        /// http://192.168.30.202:8044/WebInterface/GetOutpatientDoctors?parameters
        /// </summary>
        /// <param name="departmentCode">科室ID</param>
        /// <param name="date">日期，可为空</param>
        /// <returns></returns>
        public static JObject GetOutpatientDoctors(string departmentCode, string date)
        {
            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutpatientDoctors?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"DepartmentCode\":\"{0}\",", departmentCode);
            body.AppendFormat("\"Date\":\"{0}\"", date);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            obj_return = CommonBLL.HttpPost_CZHP(url);
            return obj_return;
        }

        /// <summary>
        /// 获取医生排班
        /// http://192.168.30.202:8044/WebInterface/GetOutPatientWorkSchedules?parameters
        /// </summary>
        /// <param name="doctorCode">医生ID</param>
        /// <param name="days">天数</param>
        /// <returns></returns>
        public static JObject GetOutPatientWorkSchedules(string doctorCode, string days)
        {
            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutPatientWorkSchedules?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"DoctorCode\":\"{0}\",", doctorCode);
            body.AppendFormat("\"Days\":\"{0}\"", days);
            body.Append("}");
            CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "1：获取医生排班请求明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "2：获取医生排班请求密文：\r\n" + url);
            obj_return = CommonBLL.HttpPost_CZHP(url);
            CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "3：获取医生排班返回明文：\r\n" + CommonBLL.ConvertJsonString(obj_return.ToString()));
            return obj_return;
        }

        /// <summary>
        ///  获取医生排班 返回剩余可预约数
        ///   http://192.168.30.202:8044/WebInterface/GetOutPatientWorkSchedules?parameters
        /// </summary>
        /// <param name="doctorCode">医生ID</param>
        /// <param name="days"></param>
        /// <param name="workId"></param>
        /// <param name="resourceid"></param>
        /// <param name="count"></param>
        /// <param name="appstate"></param>
        /// <returns></returns>
        public static JObject GetOutPatientWorkSchedules(string doctorCode, int days, string workId, string resourceid, out int count, out int appstate)
        {
            count = 99;
            appstate = 0;
            try
            {
                JObject obj_return = new JObject();
                string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutPatientWorkSchedules?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"DoctorCode\":\"{0}\",", doctorCode);
                body.AppendFormat("\"Days\":\"{0}\"", days);
                body.Append("}");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "1：获取医生排班请求明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData += "\"}";
                url += postData;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "2：获取医生排班请求密文：\r\n" + url);
                obj_return = CommonBLL.HttpPost_CZHP(url);
                string code = obj_return["code"].ToString();
                if (string.Equals(code, "1"))
                {
                    if (obj_return["result"] != null)
                    {
                        var mJObj = JArray.Parse(obj_return["result"].ToString());
                        //List<Work> works = new List<Work>();
                        foreach (var drv in mJObj)
                        {
                            var mJObj_no = JArray.Parse(drv["WorkDetails"].ToString());
                            if (string.Equals(workId, drv["Code"].ToString()))
                            {
                                int icount = 0;
                                foreach (var drvDetail in mJObj_no)
                                {
                                    string icode = drvDetail["Code"].ToString();
                                    string istate = drvDetail["AppointmentState"].ToString();
                                    //获取排班剩余可预约数
                                    if (istate == "0")
                                    {
                                        icount++;
                                    }
                                    // 遍历判断该预约的号源是否存在
                                    //不存在 号源不存在
                                    //存在判断号源状态 0为可预约，不为0说明是无效号源 直接返回。 
                                    //  CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "号源ID：" + icode + " 请求号源ID：" + resourceid + " " + string.Equals(icode, resourceid));
                                    if (string.Equals(icode, resourceid))
                                    {
                                        // CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "号源状态：" + istate + " 判断值：" + (istate != "0"));
                                        if (istate == "0")
                                        {
                                            appstate = 0;//号源未被预约
                                        }
                                        else
                                        {
                                            appstate = 2;//号源已经被预约
                                        }

                                    }
                                }
                                count = icount;
                            }
                            else
                            {
                                appstate = 3;//找不到患者当前预约的排班
                            }
                        }
                    }
                }
                else
                {
                    appstate = 3;//获取医生排班信息失败!
                }
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "预约状态：" + appstate + " 剩余可预约数：" + count);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        /// <summary>
        ///  获取医生排班 返回剩余可预约数
        ///   http://192.168.30.202:8044/WebInterface/GetOutPatientWorkSchedules?parameters
        /// </summary>
        /// <param name="doctorCode">医生ID</param>
        /// <param name="days">天数</param>
        /// <param name="workId">提交预约的排班ID</param>
        /// <param name="resourceid">提交预约的号源</param>
        /// <param name="count">剩余可预约数</param>
        /// <param name="appstate">预约状态 0未预约 4停诊</param>
        /// <returns></returns>
        public static JObject GetOutPatientWorkSchedulesNew(DateTime visitdate, string doctorCode, int days, string workId,
            string resourceid, out int count, out int appstate, out string resourceidNew, out string inumNew, out string timeNew)
        {
            count = 99;
            appstate = 0;
            resourceidNew = "";//新的号源ID
            inumNew = "";//新的号源序号
            timeNew = "";//新的号源时间

            // DateTime dateNow = Convert.ToDateTime(DateTime.Now.AddMinutes(5).ToString("HH:00"));
            DateTime dateEnd = Convert.ToDateTime("18:00");
            try
            {
                JObject obj_return = new JObject();
                string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutPatientWorkSchedules?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"DoctorCode\":\"{0}\",", doctorCode);
                body.AppendFormat("\"Days\":\"{0}\"", days);
                body.Append("}");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "1：获取医生排班请求明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData += "\"}";
                url += postData;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "2：获取医生排班请求密文：\r\n" + url);
                obj_return = CommonBLL.HttpPost_CZHP(url);
                string code = obj_return["code"].ToString();
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "3：获取医生排班返回code：" + code
                    + "。result长度：" + obj_return["result"].ToString().Length + "。\r\n");
                if (string.Equals(code, "1"))
                {
                    if (obj_return["result"] != null && obj_return["result"].ToString().Length > 3)
                    {
                        var mJObj = JArray.Parse(obj_return["result"].ToString());
                        int endtreat = 0;
                        foreach (var drv in mJObj)
                        {
                            string workdate = drv["Date"].ToString();
                            var mJObj_no_old = JArray.Parse(drv["WorkDetails"].ToString());
                            //按照序号排序
                            var mJObj_no = new JArray(mJObj_no_old.OrderBy(x => x["Code"]));
                            //CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "排序后的号源列表：\r\n"
                            //+ mJObj_no.ToString());
                            if (string.Equals(workId, drv["Code"].ToString()))
                            {
                                endtreat = drv["EndTreat"].ToString() == "False" ? 0 : 1;
                                if (string.Equals(endtreat, 1))
                                {
                                    appstate = 4;
                                    return null;
                                }
                                int icount = 0;
                                string idcodes = string.Empty;
                                foreach (var drvDetail in mJObj_no)
                                {
                                    string icode = drvDetail["Code"].ToString();
                                    string inum = drvDetail["AppointmentOrder"].ToString();
                                    string istate = drvDetail["AppointmentState"].ToString();
                                    string stime = drvDetail["TimeSection"]["StartTime"].ToString();
                                    string etime = drvDetail["TimeSection"]["EndTime"].ToString();
                                    idcodes += string.Format("{0},{1}|", icode, istate);
                                    //DateTime startTime = Convert.ToDateTime(stime);
                                    //遍历所有号源，获取排班剩余可预约数count值
                                    if (istate == "0")
                                    {
                                        //郭先菊 特殊处理
                                        if (CommonBLL.IsAddInResourceList(doctorCode, workdate, stime))
                                            icount++;
                                    }
                                    //如果是预约，优先预约患者选择的号源,如果已预约，则以患者选择的号源时间为基准，向后顺延，直到找到合适的号源。
                                    if (!string.Equals(visitdate.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd")))
                                    {
                                        if (istate == "0" && string.Compare(icode, resourceid) >= 0)
                                        {
                                            if (string.IsNullOrEmpty(resourceidNew) && string.IsNullOrEmpty(inumNew))
                                            {
                                                appstate = 0;//号源未被预约
                                                resourceidNew = icode;
                                                inumNew = inum;
                                                timeNew = string.Format("{0}~{1}", stime, etime);
                                            }
                                        }
                                    }
                                    //如果是当天号 获取最近一次的号源和序号返回
                                    else if (string.Equals(visitdate.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd")))
                                    {
                                        //08:09>=07:55 && 07:55<=08:13
                                        //16:37>=07:55 && 07:55<=16:42
                                        //2020年5月12号 删除时间校验 
                                        //if (istate == "0" && startTime >= dateNow && dateNow <= dateEnd)
                                        if (istate == "0")
                                        {
                                            if (string.IsNullOrEmpty(resourceidNew) && string.IsNullOrEmpty(inumNew))
                                            {
                                                appstate = 0;//号源未被预约
                                                resourceidNew = icode;
                                                inumNew = inum;
                                                timeNew = string.Format("{0}~{1}", stime, etime);
                                            }
                                        }
                                    }
                                }
                                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, workId + "，排序后的号源&状态列表：\r\n" + idcodes);
                                count = icount;
                            }
                        }
                    }
                    else
                    {
                        CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "4：获取医生排班返回明文：\r\n"
                            + obj_return.ToString());
                        appstate = 3;//获取医生排班信息失败!
                        count = 0;
                    }
                }
                else
                {
                    appstate = 3;//获取医生排班信息失败!
                    count = 0;
                }
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "预约状态：" + appstate + " 剩余可预约数：" + count);
                return obj_return;
            }
            catch (Exception ex)
            {
                appstate = -200;
                count = -200;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "GetOutPatientWorkSchedulesNew异常：\r\n" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        ///【弃用】 获取医生所有排班
        /// http://192.168.30.202:8044/WebInterface/GetOutPatientAllWorkSchedules?parameters
        /// </summary>
        /// <param name="days">天数</param>
        /// <returns></returns>
        public static JObject GetOutPatientAllWorkSchedules(string days)
        {
            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetOutPatientAllWorkSchedules?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"Days\":\"{0}\"", days);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            obj_return = CommonBLL.HttpPost_CZHP(url);
            return obj_return;
        }

        /// <summary>
        /// 预约挂号接口 扣款之后才能调用
        /// http://192.168.30.202:8044/WebInterface/MakeOutPatientAppointment?parameters=
        /// </summary>
        /// <param name="AppointmentCode">号源ID：20170707002028550161</param>
        /// <param name="PatientId">病人ID：140431196404160014</param>
        /// <param name="PatientName">病人姓名：张云强</param>
        /// <param name="IdentityCard">身份证号码：140431196404160014</param>
        /// <param name="Birthday">出生日期：1964-04-16</param>
        /// <param name="Gender">性别：男  request.gender == "1" ? "男" : "女"</param>
        /// <param name="Age">年龄：53 request.birth.Trim() == "" ? "1" : CommonBLL.GetAgeByBirthdate(Convert.ToDateTime(request.birth))</param>
        /// <param name="Telephone">手机号码：13994620405</param>
        /// <param name="Address">地址：山西省长治市沁源县</param>
        /// <param name="PatientCode">病人编码</param>
        /// <param name="PatientCardCode">病人卡信息</param>
        /// <param name="AgeUnit">年龄单位：岁</param>
        /// <param name="AppointmentSource">来源：健康山西</param>
        /// <returns></returns>
        public static JObject MakeOutPatientAppointment(string AppointmentCode, string PatientId, string PatientName, string IdentityCard, string Birthday
            , string Gender, string Age, string Telephone, string Address, string PatientCode, string PatientCardCode, string AgeUnit,
            string AppointmentSource)
        {
            string url_getorder = CommonBLL.GetConfig("CZHP_ADDR") + "MakeOutPatientAppointment?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();

            head.Append("{head:\"\"");
            body.Append(" {");
            body.AppendFormat("\"AppointmentCode\":\"{0}\",", AppointmentCode);
            body.Append("\"Patient\": {");
            body.AppendFormat("\"PatientId\": \"{0}\",", PatientId);
            body.AppendFormat("\"PatientName\": \"{0}\",", PatientName);
            body.AppendFormat("\"IdentityCard\": \"{0}\",", IdentityCard);
            body.AppendFormat("\"Birthday\": \"{0}\",", Birthday);
            body.AppendFormat("\"Gender\": \"{0}\",", Gender);
            body.AppendFormat("\"Age\": \"{0}\",", Age);
            body.AppendFormat("\"Telephone\": \"{0}\",", Telephone);
            body.AppendFormat("\"Address\": \"{0}\",", Address);
            body.Append("\"PatientCode\": \"\",");
            body.Append("\"PatientCardCode\": \"\",");
            body.Append("\"AgeUnit\": \"岁\"");
            body.Append("},");
            body.AppendFormat("\"AppointmentSource\": \"{0}\"", AppointmentSource);
            body.Append("}");
            CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "1：预约挂号接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
            string postData_getorder = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData_getorder += "\"}";
            url_getorder += postData_getorder;
            CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "2：预约挂号接口请求密文：\r\n" + url_getorder);
            JObject obj_getorder = CommonBLL.HttpPost_CZHP(url_getorder);
            CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "3：预约挂号接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj_getorder.ToString()));
            return obj_getorder;
        }

        /// <summary>
        /// 查询订单状态接口 支付接口、预约执行情况接口调用
        /// http://192.168.30.202:8044/WebInterface/GetAppointmentByOrderId?parameters=
        /// </summary>
        /// <param name="orderid">医院侧订单号 pt3438224</param>
        /// <returns></returns>
        public static JObject GetAppointmentByOrderId(string orderid)
        {
            try
            {
                JObject obj_return = new JObject();
                string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetAppointmentByOrderId?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"OrderId\":\"{0}\",", orderid);
                body.Append("}");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "1：预约挂号查询订单请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData += "\"}";
                url += postData;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "2：预约挂号查询订单请求密文：\r\n" + url);
                obj_return = CommonBLL.HttpPost_CZHP(url);
                CommonBLL.WriteFile_New(CommonBLL.bizCode_payResult, "3：预约挂号查询订单返回明文：\r\n" + obj_return);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        #endregion

        #region 住院服务

        /// <summary>
        /// 查询患者住院记录 获取患者最新的住院次数
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <returns></returns>
        public static JObject GetInhospitalPatientHistoryFeeInfo(string patientCode)
        {
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
               string.Format("获取患者住院次数开始：{0}，住院号：{1}"
               , DateTime.Now, patientCode));

            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetInhospitalPatientHistoryFeeInfo?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"PatientCode\":\"{0}\"", patientCode);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;

            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
              string.Format("获取患者住院次数请求报文，住院号：{0}，请求url：\r\n {1}", patientCode, url));

            obj_return = CommonBLL.HttpPost_CZHP(url);

            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
              string.Format("获取患者住院次数结束：{0}，住院号：{1}"
              , DateTime.Now, patientCode));

            //CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
            //  string.Format("获取患者住院次数返回报文，住院号：{0}，返回报文\r\n{1}",
            //patientCode, CommonBLL.ConvertJsonString(obj_return.ToString())));
            return obj_return;
        }

        /// <summary>
        /// 获取住院患者信息
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <returns></returns>
        public static JObject GetInhospitalPatientInfo(string patientCode, string hospitalizedTimes)
        {
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
               string.Format("获取住院患者开始：{0}，患者ID：{1}-{2}"
               , DateTime.Now, patientCode, hospitalizedTimes));

            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetInhospitalPatientInfo?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"PatientCode\":\"{0}\",", patientCode);
            body.AppendFormat("\"HospitalizedTimes\":\"{0}\"", hospitalizedTimes);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
             string.Format("获取患者住院患者请求报文，患者ID：{0}-{1}，请求url：\r\n{2}"
             , patientCode, hospitalizedTimes, url));

            obj_return = CommonBLL.HttpPost_CZHP(url);

            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
              string.Format("获取住院患者结束：{0}，患者ID：{1}-{2}"
              , DateTime.Now, patientCode, hospitalizedTimes));

            // CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
            //  string.Format("获取患者住院患者返回报文，患者ID：{0}-{1}，返回报文\r\n{2}",
            //patientCode, hospitalizedTimes, CommonBLL.ConvertJsonString(obj_return.ToString())));
            return obj_return;
        }

        /// <summary>
        /// 【暂时不用】获取住院患者历史记录
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <returns></returns>
        public static JObject GetInhospitalHistory(string patientCode, string hospitalizedTimes)
        {
            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetInhospitalHistory?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"PatientCode\":\"{0}\",", patientCode);
            body.AppendFormat("\"HospitalizedTimes\":\"{0}\"", hospitalizedTimes);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            obj_return = CommonBLL.HttpPost_CZHP(url);
            return obj_return;
        }

        /// <summary>
        /// 获取费用清单/明细
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <param name="prescriptionCode">处方号</param>
        /// <param name="adviceIdList">医嘱ID数组</param>
        /// <returns></returns>
        public static JObject GetInhospitalPatientFeeDetailInfo(string patientCode, string hospitalizedTimes, string prescriptionCode, string adviceIdList)
        {
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
                string.Format("获取患者费用清单开始：{0}，患者ID：{1}-{2}"
                , DateTime.Now, patientCode, hospitalizedTimes));

            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetInhospitalPatientFeeDetailInfo?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"PatientCode\":\"{0}\",", patientCode);
            body.AppendFormat("\"HospitalizedTimes\":\"{0}\",", hospitalizedTimes);
            body.AppendFormat("\"PrescriptionCode\":\"{0}\",", prescriptionCode);
            body.AppendFormat("\"AdviceIdList\":\"{0}\"", adviceIdList);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(),
                HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
            string.Format("获取患者费用清单请求报文，患者ID：{0}-{1}，请求url：\r\n{2}"
            , patientCode, hospitalizedTimes, url));

            obj_return = CommonBLL.HttpPost_CZHP(url);

            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
               string.Format("获取患者费用清单结束：{0}，患者ID：{1}-{2}"
               , DateTime.Now, patientCode, hospitalizedTimes));

            // CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
            //  string.Format("获取患者费用清单返回报文，患者ID：{0}-{1}，返回报文\r\n{2}",
            //patientCode, hospitalizedTimes, CommonBLL.ConvertJsonString(obj_return.ToString())));
            return obj_return;
        }

        /// <summary>
        /// 获取费用汇总
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <returns></returns>
        public static JObject GetInhospitalPatientTotalFeeInfo(string patientCode, string hospitalizedTimes)
        {
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
               string.Format("获取患者费用汇总开始：{0}，患者ID：{1}-{2}"
               , DateTime.Now, patientCode, hospitalizedTimes));

            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetInhospitalPatientTotalFeeInfo?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"PatientCode\":\"{0}\",", patientCode);
            body.AppendFormat("\"HospitalizedTimes\":\"{0}\"", hospitalizedTimes);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
          string.Format("获取患者费用汇总请求报文，患者ID：{0}-{1}，请求url：\r\n{2}"
          , patientCode, hospitalizedTimes, url));

            obj_return = CommonBLL.HttpPost_CZHP(url);

            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
              string.Format("获取患者费用汇总结束：{0}，患者ID：{1}-{2}"
              , DateTime.Now, patientCode, hospitalizedTimes));

            //  CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
            //  string.Format("获取患者费用汇总返回报文，患者ID：{0}-{1}，返回报文\r\n{2}",
            //patientCode, hospitalizedTimes, CommonBLL.ConvertJsonString(obj_return.ToString())));
            return obj_return;
        }

        /// <summary>
        /// 查询检验报告列表
        /// </summary>
        /// <param name="parameterType">-0-就诊号,1-住院号,2-处方号,3-条码号,9-其它</param>
        /// <param name="parameter">就诊号/住院号/申请单号(处方号)/其它</param>
        /// <returns></returns>
        public static JObject GetTestReportMainId(string parameterType, string parameter)
        {
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
                string.Format("获取检验报告列表开始：{0}，住院号：{1}"
                , DateTime.Now, parameter));

            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetTestReportMainId?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"ParameterType\":\"{0}\",", parameterType);
            body.AppendFormat("\"Parameter\":\"{0}\"", parameter);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
            string.Format("获取检验报告列表请求报文，住院号：{0}，请求url：\r\n{1}"
                , parameter, url));

            obj_return = CommonBLL.HttpPost_CZHP(url);

            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
               string.Format("获取检验报告列表结束：{0}，住院号：{1}"
               , DateTime.Now, parameter));

           //   CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
           //  string.Format("获取检验报告列表返回报文，住院号：{0}，返回报文\r\n{1}",
           //parameter, CommonBLL.ConvertJsonString(obj_return.ToString())));
            return obj_return;
        }

        /// <summary>
        /// 查询检验报告明细 GetTestReportContent ?parameters={"MainID":"1712061180sh|03010118"}
        /// </summary>
        /// <param name="mainID">检验报告条目ID</param>
        /// <returns></returns>
        public static JObject GetTestReportContent(string mainID)
        {
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
                string.Format("获取检验报告明细开始：{0}，报告ID：{1}"
                , DateTime.Now, mainID));

            JObject obj_return = new JObject();
            string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetTestReportContent?parameters=";
            StringBuilder head = new StringBuilder();
            StringBuilder body = new StringBuilder();
            head.Append("{head:\"\"");
            body.Append("{");
            body.AppendFormat("\"MainID\":\"{0}\"", mainID);
            body.Append("}");
            string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
            postData += "\"}";
            url += postData;
            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
          string.Format("获取检验报告明细请求报文，报告ID：{0}，请求url：\r\n{1}"
              , mainID, url));

            obj_return = CommonBLL.HttpPost_CZHP(url);

            CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
             string.Format("获取检验报告明细结束：{0}，报告ID：{1}"
             , DateTime.Now, mainID));

            //CommonBLL.WriteFile_New(CommonBLL.bizCode_ZYFU,
            //string.Format("获取检验报告明细返回报文，报告ID：{0}，返回报文\r\n{1}",
            //mainID, CommonBLL.ConvertJsonString(obj_return.ToString())));
            return obj_return;
        }
        #endregion

        #region 新接口 透传
        public static string Transparent(string postData, string method)
        {
            try
            {
                string url = CommonBLL.GetConfig("CZHP_ADDR2") + method;
                CommonBLL.WriteLog(string.Format("新接口透传，调用地址: \r\n{0}\r\n请求报文:\r\n{1}\r\n", url, postData));
                string returnStr = CommonBLL.HttpPost_JSON(url, postData);
                CommonBLL.WriteLog(string.Format("新接口透传，返回原始报文: \r\n{0}\r\n", returnStr));
                return returnStr;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        #endregion

        #endregion

        #region 模拟数据返回

        #region 预约挂号&支付
        /// <summary>
        /// 获取医生排班 返回剩余可预约数
        /// http://192.168.30.202:8044/WebInterface/GetOutPatientWorkSchedules?parameters
        /// </summary>
        /// <param name="doctorCode">医生ID</param>
        /// <param name="days">天数</param>
        /// <param name="workId">排班ID</param>
        /// <param name="count">剩余可预约数</param>
        /// <returns></returns>
        public static JObject GetOutPatientWorkSchedules_Test(string doctorCode, int days, string workId, string resourceid, out int count, out int appstate)
        {
            count = 99;
            appstate = 0;
            try
            {
                JObject obj_return = new JObject();

                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\长治和平排班&号源报文_单个医生7天.txt";
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                string code = obj_return["code"].ToString();
                if (string.Equals(code, "1"))
                {
                    if (obj_return["result"] != null)
                    {
                        var mJObj = JArray.Parse(obj_return["result"].ToString());
                        List<Work> works = new List<Work>();
                        foreach (var drv in mJObj)
                        {
                            var mJObj_no = JArray.Parse(drv["WorkDetails"].ToString());
                            if (string.Equals(workId, drv["Code"].ToString()))
                            {
                                int icount = 0;
                                foreach (var drvDetail in mJObj_no)
                                {
                                    string icode = drvDetail["Code"].ToString();
                                    string istate = drvDetail["AppointmentState"].ToString();
                                    //获取排班剩余可预约数
                                    if (istate == "0")
                                    {
                                        icount++;
                                    }
                                    // 遍历判断该预约的号源是否存在
                                    //不存在 号源不存在
                                    //存在判断号源状态 0为可预约，不为0说明是无效号源 直接返回。 
                                    CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "号源ID：" + icode + " 请求号源ID：" + resourceid + " " + string.Equals(icode, resourceid));
                                    if (string.Equals(icode, resourceid))
                                    {
                                        CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "号源状态：" + istate + " 判断值：" + (istate != "0"));
                                        if (istate == "0")
                                        {
                                            appstate = 0;
                                        }
                                        else
                                        {
                                            appstate = 2;
                                        }

                                    }
                                }
                                count = icount;
                            }
                            else
                            {
                                appstate = 3;
                            }
                        }
                    }
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "预约状态：" + appstate + " 剩余可预约数：" + count);
                }
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public static JObject GetOutPatientWorkSchedulesNew_Test(DateTime visitdate, string doctorCode, int days, string workId,
string resourceid, out int count, out int appstate, out string resourceidNew, out string inumNew, out string timeNew)
        {
            count = 99;
            appstate = 0;
            resourceidNew = "";
            inumNew = "";
            timeNew = "";

            DateTime dateNow = Convert.ToDateTime(DateTime.Now.AddHours(-4).ToString("HH:00"));//患者提交预约的时间
            DateTime dateEnd = Convert.ToDateTime("18:00");//
            try
            {
                JObject obj_return = new JObject();

                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\长治和平排班&号源报文_单个医生7天.txt";
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                string code = obj_return["code"].ToString();
                if (string.Equals(code, "1"))
                {
                    if (obj_return["result"] != null)
                    {
                        var mJObj = JArray.Parse(obj_return["result"].ToString());
                        foreach (var drv in mJObj)
                        {
                            var mJObj_no = JArray.Parse(drv["WorkDetails"].ToString());
                            if (string.Equals(workId, drv["Code"].ToString()))
                            {
                                int icount = 0;
                                foreach (var drvDetail in mJObj_no)
                                {
                                    string icode = drvDetail["Code"].ToString();
                                    string inum = drvDetail["AppointmentOrder"].ToString();
                                    string istate = drvDetail["AppointmentState"].ToString();
                                    string stime = drvDetail["TimeSection"]["StartTime"].ToString();
                                    string etime = drvDetail["TimeSection"]["EndTime"].ToString();

                                    DateTime startTime = Convert.ToDateTime(stime);

                                    //遍历所有号源，获取排班剩余可预约数count值
                                    if (istate == "0")
                                    {
                                        icount++;
                                    }
                                    //如果是预约，则以患者选择的号源为准,确认该号源是否可预约
                                    if (!string.Equals(visitdate.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd")))
                                    {
                                        if (istate == "0" && string.Compare(icode, resourceid) >= 0)
                                        {
                                            if (string.IsNullOrEmpty(resourceidNew) && string.IsNullOrEmpty(inumNew))
                                            {
                                                appstate = 0;//号源未被预约
                                                resourceidNew = icode;
                                                inumNew = inum;
                                                timeNew = stime;
                                            }
                                        }
                                        //if (string.Equals(icode, resourceid))
                                        //{
                                        //    if (istate == "0")
                                        //    {
                                        //        appstate = 0;//号源未被预约
                                        //        resourceidNew = icode;
                                        //        inumNew = inum;
                                        //        timeNew = stime;
                                        //    }
                                        //    else
                                        //    {
                                        //        appstate = 2;//号源已经被预约
                                        //    }
                                        //}
                                    }
                                    //如果是当天号 获取最近一次的号源和序号返回
                                    else if (string.Equals(visitdate.ToString("yyyy-MM-dd"), DateTime.Now.ToString("yyyy-MM-dd")))
                                    {
                                        if (istate == "0" && startTime >= dateNow && dateNow <= dateEnd)
                                        {
                                            if (string.IsNullOrEmpty(resourceidNew) && string.IsNullOrEmpty(inumNew))
                                            {
                                                appstate = 0;//号源未被预约
                                                resourceidNew = icode;
                                                inumNew = inum;
                                                timeNew = stime;
                                            }
                                        }
                                    }
                                }
                                count = icount;
                            }
                        }
                    }
                }
                else
                {
                    appstate = 3;//获取医生排班信息失败!
                }
                CommonBLL.WriteFile_New(CommonBLL.bizCode_getorder, "预约状态：" + appstate + " 剩余可预约数：" + count);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public static JObject MakeOutPatientAppointment_Test(string AppointmentCode, string PatientId, string PatientName, string IdentityCard, string Birthday
            , string Gender, string Age, string Telephone, string Address, string PatientCode, string PatientCardCode, string AgeUnit,
            string AppointmentSource)
        {
            try
            {
                JObject obj_return = new JObject();
                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\长治和平预约成功模拟报文.txt";//
                                                                    //path = @"E:\HIS日志\长治和平测试报文\长治和平预约失败模拟报文.txt";//
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 查询订单状态接口 支付接口、预约执行情况接口调用
        /// http://192.168.30.202:8044/WebInterface/GetAppointmentByOrderId?parameters=
        /// </summary>
        /// <param name="orderid">医院侧订单号 pt3438224</param>
        /// <returns></returns>
        public static JObject GetAppointmentByOrderId_Test(string orderid)
        {
            try
            {
                JObject obj_return = new JObject();
                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\长治和平订单查询模拟报文.txt";//
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        #endregion

        #region 住院服务

        /// <summary>
        /// 查询患者住院记录 获取患者最新的住院次数
        /// </summary>
        /// <param name="patientCode"></param>
        /// <returns></returns>
        public static JObject GetInhospitalPatientHistoryFeeInfo_Test(string patientCode)
        {
            try
            {
                JObject obj_return = new JObject();
                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\模拟报文_住院次数.txt";//
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取住院患者信息
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <returns></returns>
        public static JObject GetInhospitalPatientInfo_Test(string patientCode, string hospitalizedTimes)
        {
            try
            {
                JObject obj_return = new JObject();
                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\模拟报文_住院患者.txt";//
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public static JObject GetInhospitalPatientFeeDetailInfo_Test(string patientCode, string hospitalizedTimes, string prescriptionCode, string adviceIdList)
        {
            try
            {
                JObject obj_return = new JObject();
                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\长治和平费用清单.txt";//
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取费用汇总
        /// </summary>
        /// <param name="patientCode">住院号</param>
        /// <param name="hospitalizedTimes">住院次数</param>
        /// <returns></returns>
        public static JObject GetInhospitalPatientTotalFeeInfo_Test(string patientCode, string hospitalizedTimes)
        {
            try
            {
                JObject obj_return = new JObject();
                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\长治和平费用汇总.txt";//
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 查询检验报告列表
        /// </summary>
        /// <param name="parameterType">0-就诊号,1-住院号,2-申请单号(处方号),3-其它</param>
        /// <param name="parameter">就诊号/住院号/申请单号(处方号)/其它</param>
        /// <returns></returns>
        public static JObject GetTestReportMainId_Test(string parameterType, string parameter)
        {
            try
            {
                JObject obj_return = new JObject();
                //获取测试文本
                string path = @"E:\HIS日志\长治和平测试报文\长治和平检验报告列表.txt";//
                string result_test = CommonBLL.GetTxt(path);
                obj_return = (JObject)JsonConvert.DeserializeObject(result_test);
                return obj_return;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        #endregion
        #endregion
    }
}
